/* =======================================================================
 * jQuery.HuicheckAll.js v1.0 全选与反选
 * http://www.h-ui.net/
 * Created & Modified by guojunhui
 * Date modified 2024.09.13
 * Copyright 2019-2024 郭俊辉 All rights reserved.
 * Licensed under MIT license.
 * http://opensource.org/licenses/MIT
 * ========================================================================*/
(function($) {
  $.fn.extend({
    HuicheckAll: function(options, callback) {
      // 确保options是一个对象
      if (typeof options !== 'object') {
        options = {};
      }
      
      var defaults = {
        checkboxAll: 'thead input[type="checkbox"]',
        checkbox: 'tbody input[type="checkbox"]'
      };
      
      var settings = $.extend(defaults, options);
      
      // 定义内部函数，避免重复代码
      function updateCheckedInfo(checkbox, callback) {
        var _Num = 0,
            checkedArr = [];
        checkbox.each(function() {
          if ($(this).prop("checked")) {
            checkedArr.push($(this).val());
            _Num++;
          }
        });
        var checkedInfo = {
          Number: _Num,
          checkedArr: checkedArr
        };
        // 判断是否有callback回调函数
        if (typeof callback === 'function') {
          callback(checkedInfo);
        }
      }
      
      return this.each(function() {
        var that = $(this);
        var $checkboxAll = that.find(settings.checkboxAll);
        var $checkbox = that.find(settings.checkbox);
        
        $checkboxAll.on("click", function() {
          var isChecked = $(this).prop("checked");
          $checkbox.prop("checked", isChecked);
          updateCheckedInfo($checkbox, callback);
        });
        
        $checkbox.on("click", function() {
          var allLength = $checkbox.length;
          var checkedLength = $checkbox.filter(":checked").length;
          $checkboxAll.prop("checked", allLength === checkedLength);
          updateCheckedInfo($checkbox, callback);
        });
      });
    }
  });
})(jQuery);